<template>
  <div class="business-create">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>新增业务</span>
          <el-button @click="goBack">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
        style="max-width: 800px"
        :disabled="loading"
      >
        <el-form-item label="客户" prop="customerId">
          <el-select
            v-model="formData.customerId"
            filterable
            remote
            reserve-keyword
            placeholder="请搜索并选择客户"
            :remote-method="searchCustomer"
            :loading="customerLoading"
            @change="handleCustomerChange"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="业务类型" prop="type">
          <el-input 
            v-model="formData.type" 
            placeholder="请输入业务类型" 
            clearable
          />
        </el-form-item>

        <el-form-item label="业务内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="4"
            placeholder="请输入业务内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="submitForm"
            :loading="loading"
          >
            提交
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { createBusiness } from '@/api/business'
import { getCustomerList } from '@/api/customer'

const router = useRouter()

const formRef = ref()
const loading = ref(false)
const customerLoading = ref(false)
const customerOptions = ref([])

const formData = ref({
  customerId: '',
  type: '',
  content: ''
})

const rules = {
  customerId: [
    { required: true, message: '请选择客户', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请输入业务类型', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入业务内容', trigger: 'blur' },
    { min: 5, message: '业务内容至少5个字符', trigger: 'blur' }
  ]
}

// 搜索客户
const searchCustomer = async (query) => {
  if (query) {
    customerLoading.value = true
    try {
      const res = await getCustomerList({ name: query, page: 1, size: 10 })
      customerOptions.value = res.data
    } catch (error) {
      ElMessage.error('搜索客户失败: ' + error.message)
    } finally {
      customerLoading.value = false
    }
  }
}

// 客户选择变化
const handleCustomerChange = (customerId) => {
  formData.value.customerId = customerId
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    
    loading.value = true
    await createBusiness(formData.value)
    
    ElMessage.success('业务创建成功')
    router.push({ name: 'BusinessList' })
    
  } catch (error) {
    if (error.response) {
      ElMessage.error(`创建失败: ${error.response.data.message || '服务器错误'}`)
    } else if (!error.message.includes('validate')) {
      ElMessage.error(`创建失败: ${error.message}`)
    }
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  formRef.value.resetFields()
  customerOptions.value = []
}

// 返回列表页
const goBack = () => {
  router.push({ name: 'BusinessList' })
}

// 初始化加载客户列表
onMounted(() => {
  searchCustomer('')
})
</script>

<style scoped>
.business-create {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}
</style>